<template>
  <div class="app-container">
    <el-row :gutter="20" class="main-content">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!--部门数据-->
        <pane size="20" min-size="15">
          <el-col>
            <div class="head-container">
              <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search"
                style="margin-bottom: 20px" />
            </div>
            <div class="head-container">
              <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false"
                :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
                @node-click="handleNodeClick" />
            </div>
          </el-col>
        </pane>

        <!--工单数据-->
        <pane size="80" min-size="70">
          <el-col>
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
              label-width="80px" class="search-form">
              <el-form-item label="报修类型" prop="repairType">
                <el-select v-model="queryParams.repairType" placeholder="请选择报修类型" clearable>
                  <el-option label="门禁故障" value="门禁故障" />
                  <el-option label="网络故障" value="网络故障" />
                  <el-option label="设备故障" value="设备故障" />
                  <el-option label="其他" value="其他" />
                </el-select>
              </el-form-item>
              <el-form-item label="状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                  <el-option label="待派单" value="待派单" />
                  <el-option label="已派单" value="已派单" />
                  <el-option label="处理中" value="处理中" />
                  <el-option label="已完成" value="已完成" />
                  <el-option label="已取消" value="已取消" />
                </el-select>
              </el-form-item>
              <el-form-item label="报障人电话" prop="createPhone" label-width="100px">
                <el-input v-model="queryParams.createPhone" placeholder="请输入报障人电话" clearable />
              </el-form-item>
              <el-form-item label="门禁编码" prop="mjbm">
                <el-input v-model="queryParams.mjbm" placeholder="请输入门禁编码" clearable />
              </el-form-item>
              <el-form-item label="宽带账号" prop="kdzh">
                <el-input v-model="queryParams.kdzh" placeholder="请输入宽带账号" clearable />
              </el-form-item>
              <el-form-item label="创建时间" prop="createDateRange" label-width="80px">
                <el-date-picker
                  v-model="createDateRange"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  @change="handleDateRangeChange"
                  clearable
                  style="width: 350px"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8" style="margin-top: 10px;">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                  >新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                  >修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                    @click="handleDelete">删除</el-button>
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
              </el-col>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>

            <div class="table-container" v-sticky-header="{ offset: 50 }">
              <el-table v-loading="loading" border :data="repairList" @selection-change="handleSelectionChange" stripe :height="tableHeight">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                    >修改</el-button>
                  <el-button size="mini" type="text" icon="el-icon-user" @click="handleAssign(scope.row)"
                    >指派</el-button>
                  <el-button v-if="scope.row.status === '已完成'" size="mini" type="text" icon="el-icon-view"
                    @click="handleCheck(scope.row)">抽查</el-button>
                  <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                    >删除</el-button>
                </template>
              </el-table-column>
              <!-- 重要字段放在最前面 -->
              <el-table-column label="报修内容" align="center" prop="repairContent" width="200"
                :show-overflow-tooltip="true" />
                <el-table-column label="维修结果" align="center" prop="responseContent" width="200"
                :show-overflow-tooltip="true" />
              <el-table-column label="报修类型" align="center" prop="repairType" width="100" />
              <el-table-column label="GUID码" align="center" prop="jguid" width="150" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span>{{ scope.row.jguid || scope.row.xguid || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="指派人员" align="center" prop="operaUseNickname" width="100">
                <template slot-scope="scope">
                  <span>{{ scope.row.operaUseNickname || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="状态" align="center" prop="status" width="100">
                <template slot-scope="scope">
                  <el-tag :type="getStatusTagType(scope.row.status)">
                    {{ scope.row.status || '待派单' }}
                  </el-tag>
                </template>
              </el-table-column>
              <!-- 其他字段 -->
              <el-table-column label="工单编号" align="center" prop="id" width="100" />
              <el-table-column label="合同编号" align="center" prop="htbh" width="120">
                <template slot-scope="scope">
                  <span>{{ scope.row.htbh || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="房产资料" align="center" prop="jzxm" width="120">
                <template slot-scope="scope">
                  <span>{{ scope.row.jzxm || '未知用户' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="地址信息" align="center" width="200" show-overflow-tooltip>
                <template slot-scope="scope">
                  <div>
                    <div v-if="scope.row.provinceName || scope.row.cityName || scope.row.districtName">
                      {{ [scope.row.provinceName, scope.row.cityName, scope.row.districtName].filter(Boolean).join(' ')
                      }}
                    </div>
                    <div v-if="scope.row.streetName || scope.row.villageName">
                      {{ [scope.row.streetName, scope.row.villageName].filter(Boolean).join(' ') }}
                    </div>
                    <div v-if="scope.row.address" class="address-detail">
                      {{ scope.row.address }}
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="报障电话" align="center" width="150">
                <template slot-scope="scope">
                  <span class="phone-text">{{ scope.row.createPhone || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="宽带账号" align="center" prop="kdzh" width="150">
                <template slot-scope="scope">
                  <span>{{ scope.row.kdzh || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="宽带密码" align="center" prop="kdmm" width="120">
                <template slot-scope="scope">
                  <span>{{ scope.row.kdmm || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="新GUID码" align="center" prop="xguid" width="150" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span>{{ scope.row.xguid || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="门禁编码" align="center" prop="mjbm" width="120">
                <template slot-scope="scope">
                  <span>{{ scope.row.mjbm || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="创建人" align="center" prop="createByNickname" width="100">
                <template slot-scope="scope">
                  <span>{{ scope.row.createByNickname || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="创建时间" align="center" prop="createTime" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
                <template slot-scope="scope">
                  <span>{{ scope.row.updateTime ? parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}') : '-' }}</span>
                </template>
              </el-table-column>
            </el-table>
            </div>

            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize" @pagination="getList" />
          </el-col>
        </pane>
      </splitpanes>
    </el-row>

    <!-- 添加或修改报修工单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="房产资料" prop="adslId">
          <el-select 
            v-model="form.adslId" 
            placeholder="请选择房产资料" 
            filterable 
            remote 
            reserve-keyword 
            :remote-method="remoteSearchAdsl"
            :loading="adslSearchLoading"
            @focus="handleAdslFocus"
            clearable>
            <el-option v-for="item in adslOptions" :key="item.id" :label="`${item.jzxm || item.landlordName || '未知用户'} - ${item.address}`"
              :value="item.id">
              <span style="float: left">{{ item.jzxm || item.landlordName || '未知用户' }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.address }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报修类型" prop="repairType">
          <el-select v-model="form.repairType" placeholder="请选择报修类型">
            <el-option label="门禁故障" value="门禁故障" />
            <el-option label="网络故障" value="网络故障" />
            <el-option label="设备故障" value="设备故障" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="报修内容" prop="repairContent">
          <el-input v-model="form.repairContent" type="textarea" placeholder="请输入报修内容" :rows="4" />
        </el-form-item>
        <el-form-item label="报障人电话" prop="createPhone">
          <el-input v-model="form.createPhone" placeholder="请输入手机号或固定电话" maxlength="20" />
        </el-form-item>
        <el-form-item label="报修图片" prop="repairImgs">
          <FileUpload v-model="form.repairImgs" :limit="5" :file-size="2" :file-type="['jpg', 'jpeg', 'png', 'gif']"
            :is-show-tip="true" />
        </el-form-item>
      </el-form>

      <!-- 工单处理时间线 -->
      <div v-if="form.id && form.logs && form.logs.length > 0" class="timeline-section">
        <div class="timeline-title">
          <i class="el-icon-time"></i>
          处理记录
        </div>
        <el-timeline>
          <el-timeline-item v-for="(log, index) in form.logs" :key="log.id"
            :timestamp="parseTime(log.createTime, '{y}-{m}-{d} {h}:{i}:{s}')" :type="getTimelineItemType(log.status)"
            :color="getTimelineItemColor(log.status)" :icon="getTimelineItemIcon(log.status)">
            <div class="timeline-content">
              <div class="timeline-status">
                <el-tag :type="getStatusTagType(log.status)" size="small">
                  {{ log.status }}
                </el-tag>
              </div>
              <div class="timeline-info">
                <span class="timeline-time">{{ parseTime(log.createTime, '{m}-{d} {h}:{i}') }}</span>
                <span class="timeline-user">操作人：{{ log.createByNickName || '系统' }}</span>
              </div>
              <div v-if="log.log" class="timeline-log">
                {{ log.log }}
              </div>
              <div v-if="log.img" class="timeline-image">
                <el-image v-for="(imgUrl, imgIndex) in log.img.split(',')" :key="imgIndex" :src="baseURL + imgUrl"
                  :preview-src-list="log.img.split(',').map(url => baseURL + url)" fit="cover"
                  style="width: 100px; height: 60px; border-radius: 4px; margin-right: 8px; margin-bottom: 8px;" />
              </div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 指派工单对话框 -->
    <el-dialog title="指派工单" :visible.sync="assignOpen" width="400px" append-to-body>
      <el-form ref="assignForm" :model="assignForm" :rules="assignRules" label-width="80px">
        <el-form-item label="工单编号" prop="repairOrderId">
          <el-input v-model="assignForm.repairOrderId" disabled />
        </el-form-item>
        <el-form-item label="指派人员" prop="operaUserId">
          <el-select v-model="assignForm.operaUserId" placeholder="请选择指派人员" filterable>
            <el-option v-for="item in userOptions" :key="item.userId" :label="item.nickName" :value="item.userId">
              <span style="float: left">{{ item.nickName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.userName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAssign" :loading="assignLoading">确 定</el-button>
        <el-button @click="cancelAssign">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 抽查工单对话框 -->
    <el-dialog title="抽查工单" :visible.sync="checkOpen" width="500px" append-to-body>
      <el-form ref="checkForm" :model="checkForm" :rules="checkRules" label-width="80px">
        <el-form-item label="工单编号" prop="repairOrderId">
          <el-input v-model="checkForm.repairOrderId" disabled />
        </el-form-item>
        <el-form-item label="抽查结果" prop="checkResult">
          <el-radio-group v-model="checkForm.checkResult">
            <el-radio label="通过">通过</el-radio>
            <el-radio label="不通过">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="抽查备注" prop="checkRemark">
          <el-input v-model="checkForm.checkRemark" type="textarea" placeholder="请输入抽查备注" :rows="3" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCheck" :loading="checkLoading">确 定</el-button>
        <el-button @click="cancelCheck">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRepair, getRepair, delRepair, addRepair, updateRepair, assignRepair } from "@/api/door/order";
import { listAdsl } from "@/api/door/adsl";
import { listUser, getRoleUsers } from "@/api/system/user";
import { deptTreeSelect } from "@/api/system/user"
import { parseTime } from '@/utils/ruoyi';
import FileUpload from "@/components/FileUpload";
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"

export default {
  name: "Repair",
  components: {
    FileUpload,
    Splitpanes,
    Pane
  },
  data() {
    return {
      // 表格高度
      tableHeight: 600,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报修工单表格数据
      repairList: [],
      // 弹出层标题
      title: "",
      // 部门名称
      deptName: "",
      // 部门树配置选项
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 部门树选项
      deptOptions: undefined,
      // 过滤掉已禁用部门树选项
      enabledDeptOptions: undefined,
      // 创建时间范围选择器
      createDateRange: null,
      // 地址树形选项
      addressTreeOptions: [],
      // 是否显示弹出层
      open: false,
      // ADSL选项
      adslOptions: [],
      // ADSL搜索加载状态
      adslSearchLoading: false,
      // ADSL搜索关键词
      adslSearchKeyword: '',
      // 防抖定时器
      adslSearchTimer: null,
      // baseURL
      baseURL: process.env.VUE_APP_BASE_API,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        repairType: null,
        status: null,
        adslId: null,
        createPhone: null,
        mjbm: null,
        kdzh: null,
        deptId: null,
        country: null,
        province: null,
        city: null,
        district: null,
        street: null,
        village: null,
        createDateS: null,
        createDateE: null
      },
      // 表单参数
      form: {},
      // 提交加载状态
      submitLoading: false,
      // 是否显示指派弹出层
      assignOpen: false,
      // 指派加载状态
      assignLoading: false,
      // 指派表单参数
      assignForm: {},
      // 用户选项
      userOptions: [],
      // 是否显示抽查弹出层
      checkOpen: false,
      // 抽查加载状态
      checkLoading: false,
      // 抽查表单参数
      checkForm: {},
      // 表单校验
      rules: {
        adslId: [
          { required: true, message: "房产资料不能为空", trigger: "change" }
        ],
        repairType: [
          { required: true, message: "报修类型不能为空", trigger: "change" }
        ],
        repairContent: [
          { required: true, message: "报修内容不能为空", trigger: "blur" }
        ],
        createPhone: [
          { 
            pattern: /^(1[3-9]\d{9}|0\d{2,3}-?\d{7,8}|\d{3,4}-?\d{7,8})$/, 
            message: "请输入正确的手机号码或固定电话", 
            trigger: "blur" 
          }
        ]
      },
      // 指派表单校验
      assignRules: {
        operaUserId: [
          { required: true, message: "指派人员不能为空", trigger: "change" }
        ]
      },
      // 抽查表单校验
      checkRules: {
        checkResult: [
          { required: true, message: "抽查结果不能为空", trigger: "change" }
        ]
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.initAdslOptions();
    this.getUserOptions();
    this.getDeptTree();
    this.getList();
  },
  mounted() {
    this.calculateTableHeight()
    window.addEventListener('resize', this.calculateTableHeight)

    // 延迟检查表头吸顶功能
    setTimeout(() => {
      this.checkStickyHeader()
    }, 1000)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.calculateTableHeight);
    // 清理定时器
    if (this.adslSearchTimer) {
      clearTimeout(this.adslSearchTimer);
    }
  },
  methods: {
    parseTime,
    // 计算表格高度
    calculateTableHeight() {
      this.$nextTick(() => {
        // 计算可用高度：视窗高度 - 顶部固定高度 - 搜索区域 - 按钮区域 - 分页高度 - 边距
        const windowHeight = window.innerHeight
        const headerHeight = 124 // 顶部导航高度
        const searchFormHeight = 80 // 搜索表单高度
        const buttonAreaHeight = 60 // 按钮区域高度
        const paginationHeight = 60 // 分页高度
        const padding = 80 // 各种边距和间距

        const availableHeight = windowHeight - headerHeight - searchFormHeight - buttonAreaHeight - paginationHeight - padding
        this.tableHeight = Math.max(500, availableHeight) // 最小高度400px
      })
    },
    // 检查表头吸顶功能
    checkStickyHeader() {
      const tableContainer = this.$el.querySelector('.table-container')
      const table = tableContainer?.querySelector('.el-table')
      const headerWrapper = table?.querySelector('.el-table__header-wrapper')

      console.log('检查表头吸顶功能:', {
        tableContainer,
        table,
        headerWrapper,
        stickyPosition: headerWrapper?.style.position,
        stickyTop: headerWrapper?.style.top
      })

      if (headerWrapper && headerWrapper.style.position !== 'sticky') {
        console.warn('表头吸顶样式未正确应用，手动设置')
        headerWrapper.style.position = 'sticky'
        headerWrapper.style.top = '50px'
        headerWrapper.style.zIndex = '99'
        headerWrapper.style.background = '#fff'
        headerWrapper.style.boxShadow = '0 2px 4px rgba(0,0,0,0.1)'
      }
    },
    /** 查询报修工单列表 */
    getList() {
      this.loading = true;
      listRepair(this.queryParams).then(response => {
        this.repairList = response.rows || [];
        this.total = response.total || 0;
        this.loading = false;
      }).catch(error => {
        console.error('获取报修工单列表失败:', error);
        this.repairList = [];
        this.total = 0;
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.downloadGet('admin-api/door/order/repair/export', {
        ...this.queryParams
      }, `repair_order_${new Date().getTime()}.xlsx`)
    },
    /** 获取ADSL选项（默认10条） */
    getAdslOptions(keyword = '') {
      const params = {
        pageNum: 1,
        pageSize: 10
      };
      
      // 如果有搜索关键词，添加搜索参数
      if (keyword) {
        // params.jzxm = keyword; // 按机主姓名搜索
        // params.landlordName = keyword; // 按房主姓名搜索
        params.address = keyword; // 按地址搜索
      }
      
      return listAdsl(params).then(response => {
        return response.rows || [];
      }).catch(error => {
        console.error('获取ADSL选项失败:', error);
        this.$message.error('获取ADSL选项失败');
        return [];
      });
    },
    
    /** 初始化ADSL选项 */
    initAdslOptions() {
      this.getAdslOptions().then(data => {
        this.adslOptions = data;
      });
    },
    
    /** 远程搜索ADSL */
    remoteSearchAdsl(query) {
      if (query !== '') {
        this.adslSearchLoading = true;
        this.adslSearchKeyword = query;
        
        // 防抖处理
        if (this.adslSearchTimer) {
          clearTimeout(this.adslSearchTimer);
        }
        
        this.adslSearchTimer = setTimeout(() => {
          this.getAdslOptions(query).then(data => {
            this.adslOptions = data;
            this.adslSearchLoading = false;
          });
        }, 300);
      } else {
        // 清空搜索时恢复默认数据
        this.initAdslOptions();
      }
    },
    
    /** 处理ADSL下拉框获得焦点 */
    handleAdslFocus() {
      // 如果没有数据或数据较少，重新加载默认数据
      if (this.adslOptions.length === 0) {
        this.initAdslOptions();
      }
    },
    /** 获取用户选项 */
    getUserOptions() {
      getRoleUsers(102).then(response => {
        this.userOptions = response.rows || [];
      }).catch(error => {
        console.error('获取用户选项失败:', error);
        this.userOptions = [];
        this.$message.error('获取用户选项失败');
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
        this.enabledDeptOptions = this.filterDisabledDept(JSON.parse(JSON.stringify(response.data)))

        // 使用部门树数据构建地址树
        this.buildAddressTreeFromDeptTree()

        this.$nextTick(() => {
          // 默认选择公司节点
          if (this.deptOptions && this.deptOptions.length > 0) {
            const companyNode = this.deptOptions[0]
            this.$refs.tree.setCurrentKey(companyNode.id)

            // 设置公司节点的地址字段
            this.setAddressFieldsFromNode(companyNode)
          }

          // 所有初始化工作完成后，统一请求一次数据
          this.handleQuery()
        })
      }).catch(error => {
        console.error('获取部门树失败:', error)
      })
    },
    // 过滤禁用的部门
    filterDisabledDept(deptList) {
      return deptList.filter(dept => {
        if (dept.disabled) {
          return false
        }
        if (dept.children && dept.children.length) {
          dept.children = this.filterDisabledDept(dept.children)
        }
        return true
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      // 先清空deptId，因为只有村级才设置deptId
      this.queryParams.deptId = null

      // 获取选中节点的完整路径并设置到查询参数中
      this.setAddressFieldsFromNode(data)

      this.handleQuery()
    },
    // 根据选中节点设置地址字段
    setAddressFieldsFromNode(selectedNode) {
      // 先清空所有地址字段
      this.queryParams.deptId = null
      this.queryParams.country = null
      this.queryParams.province = null
      this.queryParams.city = null
      this.queryParams.district = null
      this.queryParams.street = null
      this.queryParams.village = null

      // 查找选中节点的完整路径
      const nodePath = this.findNodePath(this.deptOptions, selectedNode.id)

      if (nodePath && nodePath.length > 0) {
        // 获取选中节点的层级（最后一个节点的层级）
        const selectedLevel = nodePath.length - 1
        const selectedNodeData = nodePath[selectedLevel]

        // 只设置选中节点对应层级的字段（参考ADSL组件的逻辑）
        switch (selectedLevel) {
          case 0: // 公司/国家
            this.queryParams.country = selectedNodeData.id
            break
          case 1: // 省
            this.queryParams.province = selectedNodeData.id
            break
          case 2: // 市
            this.queryParams.city = selectedNodeData.id
            break
          case 3: // 区县
            this.queryParams.district = selectedNodeData.id
            break
          case 4: // 街道/镇
            this.queryParams.street = selectedNodeData.id
            break
          case 5: // 村
            this.queryParams.village = selectedNodeData.id
            // 只有选择村的时候才设置deptId
            this.queryParams.deptId = selectedNodeData.id
            break
        }

        console.log('选中地址层级:', selectedLevel, '查询参数:', {
          selectedNode: selectedNodeData.label,
          deptId: this.queryParams.deptId,
          country: this.queryParams.country,
          province: this.queryParams.province,
          city: this.queryParams.city,
          district: this.queryParams.district,
          street: this.queryParams.street,
          village: this.queryParams.village
        })
      }
    },
    // 查找节点在树中的完整路径
    findNodePath(nodes, targetId, currentPath = []) {
      if (!nodes || !Array.isArray(nodes)) return null

      for (const node of nodes) {
        const newPath = [...currentPath, node]

        if (node.id === targetId) {
          return newPath
        }

        if (node.children && node.children.length > 0) {
          const found = this.findNodePath(node.children, targetId, newPath)
          if (found) return found
        }
      }

      return null
    },
    // 构建地址树
    buildAddressTreeFromDeptTree() {
      if (!this.enabledDeptOptions) return

      // 直接使用部门树数据作为地址树
      // 如果部门树的层次结构是公司->省->市->区->街道/镇->村
      this.addressTreeOptions = JSON.parse(JSON.stringify(this.enabledDeptOptions))
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        adslId: null,
        repairContent: null,
        repairImgs: null,
        repairType: null,
        createPhone: null
      };
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    },
    /** 搜索按钮操作 */
    // 处理时间范围变化
    handleDateRangeChange(dateRange) {
      if (dateRange && dateRange.length === 2) {
        this.queryParams.createDateS = dateRange[0]
        this.queryParams.createDateE = dateRange[1]
      } else {
        this.queryParams.createDateS = null
        this.queryParams.createDateE = null
      }
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      if (this.$refs.queryForm) {
        this.$refs.queryForm.resetFields();
      }

      // 重置地址相关参数
      this.queryParams.deptId = null;
      this.queryParams.country = null;
      this.queryParams.province = null;
      this.queryParams.city = null;
      this.queryParams.district = null;
      this.queryParams.street = null;
      this.queryParams.village = null;
      
      // 重置时间范围参数
      this.queryParams.createDateS = null;
      this.queryParams.createDateE = null;
      this.createDateRange = null;

      // 重置树选择到公司节点
      if (this.deptOptions && this.deptOptions.length > 0 && this.$refs.tree) {
        const companyNode = this.deptOptions[0];
        this.$refs.tree.setCurrentKey(companyNode.id);
        this.setAddressFieldsFromNode(companyNode);
      }

      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加报修工单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getRepair(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改报修工单";
      }).catch(error => {
        console.error('获取报修工单详情失败:', error);
        this.$message.error('获取报修工单详情失败');
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (!this.$refs["form"]) {
        this.$message.error('表单未初始化');
        return;
      }

      this.submitLoading = true;
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 只提交表单字段，过滤掉其他数据
          const submitData = {
            adslId: this.form.adslId,
            repairContent: this.form.repairContent,
            repairImgs: this.form.repairImgs,
            repairType: this.form.repairType,
            createPhone: this.form.createPhone
          };

          if (this.form.id != null) {
            // 修改时使用repairOrderId字段
            submitData.repairOrderId = this.form.id;
            updateRepair(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.submitLoading = false;
            }).catch(error => {
              console.error('修改报修工单失败:', error);
              this.$message.error('修改报修工单失败');
              this.submitLoading = false;
            });
          } else {
            // 新增时不需要传repairOrderId
            addRepair(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.submitLoading = false;
            }).catch(error => {
              console.error('新增报修工单失败:', error);
              this.$message.error('新增报修工单失败');
              this.submitLoading = false;
            });
          }
        } else {
          this.submitLoading = false;
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除报修工单编号为"' + ids + '"的数据项？').then(function () {
        return delRepair(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(error => {
        console.error('删除报修工单失败:', error);
        this.$message.error('删除报修工单失败');
      });
    },
    /** 指派按钮操作 */
    handleAssign(row) {
      this.assignForm = {
        repairOrderId: row.id,
        operaUserId: null
      };
      this.assignOpen = true;
    },
    /** 取消指派 */
    cancelAssign() {
      this.assignOpen = false;
      this.resetAssign();
    },
    /** 重置指派表单 */
    resetAssign() {
      this.assignForm = {
        repairOrderId: null,
        operaUserId: null
      };
      if (this.$refs.assignForm) {
        this.$refs.assignForm.resetFields();
      }
    },
    /** 提交指派 */
    submitAssign() {
      if (!this.$refs["assignForm"]) {
        this.$message.error('指派表单未初始化');
        return;
      }

      this.assignLoading = true;
      this.$refs["assignForm"].validate(valid => {
        if (valid) {
          assignRepair(this.assignForm).then(response => {
            this.$modal.msgSuccess("指派成功");
            this.assignOpen = false;
            this.getList();
            this.assignLoading = false;
          }).catch(error => {
            console.error('指派工单失败:', error);
            this.$message.error('指派工单失败');
            this.assignLoading = false;
          });
        } else {
          this.assignLoading = false;
        }
      });
    },
    /** 抽查按钮操作 */
    handleCheck(row) {
      this.checkForm = {
        repairOrderId: row.id,
        checkResult: null,
        checkRemark: null
      };
      this.checkOpen = true;
    },
    /** 取消抽查 */
    cancelCheck() {
      this.checkOpen = false;
      this.resetCheck();
    },
    /** 重置抽查表单 */
    resetCheck() {
      this.checkForm = {
        repairOrderId: null,
        checkResult: null,
        checkRemark: null
      };
      if (this.$refs.checkForm) {
        this.$refs.checkForm.resetFields();
      }
    },
    /** 提交抽查 */
    submitCheck() {
      if (!this.$refs["checkForm"]) {
        this.$message.error('抽查表单未初始化');
        return;
      }

      this.checkLoading = true;
      this.$refs["checkForm"].validate(valid => {
        if (valid) {
          // 这里需要调用抽查接口
          // checkRepair(this.checkForm).then(response => {
          //   this.$modal.msgSuccess("抽查成功");
          //   this.checkOpen = false;
          //   this.getList();
          //   this.checkLoading = false;
          // }).catch(error => {
          //   console.error('抽查工单失败:', error);
          //   this.$message.error('抽查工单失败');
          //   this.checkLoading = false;
          // });

          // 临时处理：如果抽查不通过，则重新指派
          if (this.checkForm.checkResult === '不通过') {
            this.$modal.msgSuccess("抽查不通过，请重新指派");
            this.checkOpen = false;
            // 打开指派弹窗
            this.handleAssign({ id: this.checkForm.repairOrderId });
          } else {
            this.$modal.msgSuccess("抽查通过");
            this.checkOpen = false;
            this.getList();
          }
          this.checkLoading = false;
        } else {
          this.checkLoading = false;
        }
      });
    },
    /** 获取时间线项目类型 */
    getTimelineItemType(status) {
      const typeMap = {
        '待派单': 'primary',
        '已派单': 'success',
        '已接单': 'warning',
        '处理中': 'warning',
        '已完成': 'success',
        '已取消': 'danger'
      };
      return typeMap[status] || 'info';
    },
    /** 获取时间线项目颜色 */
    getTimelineItemColor(status) {
      const colorMap = {
        '待派单': '#409eff',
        '已派单': '#67c23a',
        '已接单': '#e6a23c',
        '处理中': '#e6a23c',
        '已完成': '#67c23a',
        '已取消': '#f56c6c'
      };
      return colorMap[status] || '#909399';
    },
    /** 获取时间线项目图标 */
    getTimelineItemIcon(status) {
      const iconMap = {
        '待派单': 'el-icon-clock',
        '已派单': 'el-icon-user',
        '已接单': 'el-icon-tools',
        '处理中': 'el-icon-tools',
        '已完成': 'el-icon-check',
        '已取消': 'el-icon-close'
      };
      return iconMap[status] || 'el-icon-info';
    },
    /** 获取状态标签类型 */
    getStatusTagType(status) {
      const tagMap = {
        '待派单': 'info',
        '已派单': 'primary',
        '已接单': 'warning',
        '处理中': 'warning',
        '已完成': 'success',
        '已取消': 'danger'
      };
      return tagMap[status] || 'info';
    },

  }
};
</script>

<style scoped>
.main-content {
  height: calc(100vh - 124px);
  overflow: hidden;
}

.app-container {
  padding: 10px;
  height: 100%;
  overflow: hidden;
}

.default-theme {
  height: 100%;
}

.splitpanes.default-theme .splitpanes__pane {
  background-color: #fff;
  overflow: auto;
}

.splitpanes--vertical>.splitpanes__splitter {
  min-width: 6px;
}

/* 表格样式优化 */
.el-table {
  margin-top: 8px;
}

.el-table .el-table__header th {
  background-color: #f5f7fa;
}

.el-table .el-table__row:hover {
  background-color: #f0f7ff;
}

/* 表单样式优化 */
.el-dialog__body {
  padding: 20px 30px 10px 30px;
}

.search-form {
  margin-bottom: 10px;
}

.mb8 {
  margin-bottom: 8px;
}

.dialog-footer {
  text-align: right;
  padding-top: 10px;
}

/* 时间线样式 */
.timeline-section {
  margin-top: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.timeline-title {
  font-size: 16px;
  font-weight: 600;
  color: #606266;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.timeline-title i {
  margin-right: 8px;
  color: #409eff;
}

.timeline-content {
  padding: 10px 0;
}

.timeline-status {
  margin-bottom: 8px;
}

.timeline-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 12px;
  color: #909399;
}

.timeline-time {
  font-weight: 500;
  color: #606266;
}

.timeline-user {
  color: #909399;
}

.timeline-log {
  background: #fff;
  padding: 8px 12px;
  border-radius: 4px;
  border-left: 3px solid #409eff;
  margin-top: 8px;
  font-size: 13px;
  color: #606266;
  line-height: 1.5;
}

.timeline-image {
  margin-top: 8px;
}

/* 时间线组件样式优化 */
.el-timeline-item__node {
  border-radius: 50%;
}

.el-timeline-item__timestamp {
  font-size: 12px;
  color: #909399;
}

.el-timeline-item__content {
  padding-left: 10px;
}

/* 新增表格字段样式 */
.address-detail {
  color: #909399;
  font-size: 12px;
  margin-top: 2px;
}

.phone-text {
  color: #409eff;
  font-size: 12px;
  margin-top: 2px;
}

/* 表格容器样式 */
.table-container {
  position: relative;
  height: 100%;
  overflow: auto;
}

.table-container .el-table {
  width: 100%;
}

/* 强制表头吸顶样式 */
.table-container .el-table .el-table__header-wrapper {
  position: sticky !important;
  top: 50px !important;
  z-index: 99 !important;
  background: #fff !important;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1) !important;
}
</style>
